package com.yunqiao.service.api.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunqiao.common.consts.AppConsts;
import com.yunqiao.common.exception.CustomApiException;
import com.yunqiao.common.utils.PageUtils;
import com.yunqiao.common.utils.Query;
import com.yunqiao.common.utils.SmsUtils;
import com.yunqiao.common.validator.Assert;
import com.yunqiao.service.api.UserService;
import com.yunqiao.service.api.entity.*;
import com.yunqiao.service.api.form.Login;
import com.yunqiao.service.api.mapper.*;
import com.yunqiao.service.api.vo.UserVo;
import com.yunqiao.service.sys.entity.SysUserEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

	@Resource
	private UserMapper userMapper;

	@Resource
	private UserDepositMapper userDepositMapper;

	@Resource
	private ApplyDriverMapper applyDriverMapper;
	@Resource
	private ApplyPartnerMapper applyPartnerMapper;
	@Resource
	private OrderCashMapper orderCashMapper;
	@Resource
	private OrderMapper orderMapper;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {

		//各种查询条件的过滤,在此进行
		QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
		if (StringUtils.isNotEmpty(MapUtil.getStr(params, "name"))) {
			queryWrapper.and(userEntityQueryWrapper -> userEntityQueryWrapper.or().like("name", MapUtil.getStr(params, "name")).or().like("phone", MapUtil.getStr(params, "name")).or().like("id_number", MapUtil.getStr(params, "name")));
		}
		//账号状态
		String accountStatus = MapUtil.getStr(params, "accountStatus");
		if (StrUtil.isNotBlank(accountStatus)) {
			queryWrapper.eq("account_status", accountStatus);
		}

		//省
		String province = MapUtil.getStr(params, "province");
		if (StrUtil.isNotBlank(province)) {
			queryWrapper.eq("province", province);
		}
		//市
		String city = MapUtil.getStr(params, "city");

		if (StrUtil.isNotBlank(city)) {
			queryWrapper.eq("city", city);
		}

		//区
		String district = MapUtil.getStr(params, "district");
		if (StrUtil.isNotBlank(district)) {
			queryWrapper.eq("district",district);
		}

		//车辆类型
		String carTypeId = MapUtil.getStr(params, "carTypeId");
		if (StrUtil.isNotBlank(carTypeId)) {
			queryWrapper.eq("car_type_id",carTypeId);
		}

		String createTime = MapUtil.getStr(params, "createTime");
		String updateTime = MapUtil.getStr(params, "updateTime");
		if (StringUtils.isNotEmpty(createTime) && StringUtils.isNotEmpty(updateTime)) { //当开始时间用
			queryWrapper.between("create_time", DateUtil.parse(createTime, "yyyy-MM-dd"), DateUtil.parse(updateTime, "yyyy-MM-dd"));
		}

		//上级ID
		String superiorUserId = MapUtil.getStr(params, "superiorUserId");
		if (StrUtil.isNotBlank(superiorUserId)) {
			queryWrapper.eq("superior_user_id", superiorUserId);
		}
		//角色类型
		if (params.get("roleType") != null) {

			if (MapUtil.getInt(params, "roleType").equals(AppConsts.USER_ROLE_TYPE_1)) {
				queryWrapper.eq("role_type", params.get("roleType"));
			}else if(MapUtil.getInt(params, "roleType").equals(AppConsts.USER_ROLE_TYPE_2)){
				queryWrapper.eq("role_type", params.get("roleType"));
			}
			if (MapUtil.getInt(params, "roleType").equals(AppConsts.USER_ROLE_TYPE_2)) {
				//queryWrapper.in("apply_driver", AppConsts.USER_APPLY_DRIVER_1, AppConsts.USER_APPLY_DRIVER_2);
				if (params.get("sysType") != null && MapUtil.getBool(params, "sysType")) {
					SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
					ApplyPartnerEntity applyPartnerEntity = applyPartnerMapper.selectOne(new QueryWrapper<ApplyPartnerEntity>().eq("state", AppConsts.USER_APPLY_PARTNER_STATE_3)
							.eq("sys_user_id", user.getUserId()));
					if (ObjectUtil.isNotNull(applyPartnerEntity)) {
						if (StrUtil.isNotEmpty(applyPartnerEntity.getProvince())) {
							queryWrapper.eq("province", applyPartnerEntity.getProvince());
						}

						if (StrUtil.isNotEmpty(applyPartnerEntity.getCity())) {
							queryWrapper.eq("city", applyPartnerEntity.getCity());
						}

						if (StrUtil.isNotEmpty(applyPartnerEntity.getArea())) {
							queryWrapper.eq("district", applyPartnerEntity.getArea());
						}
					}
				}
			}
		}
		IPage<UserEntity> page = this.page(new Query<UserEntity>(params).getPage(), queryWrapper.orderByDesc("create_time"));
		return new PageUtils(page);
	}

	@Override
	public UserEntity details(Long id) {
		return userMapper.details(id);
	}

	@Override
	public List<Dict> getPosition() {
		List<Dict> dictList = new ArrayList<>();
		List<UserEntity> list = this.userMapper.selectList(new QueryWrapper<UserEntity>()
				.eq("deleted", 0)
				.eq("role_type", AppConsts.USER_ROLE_TYPE_2));

		if (list != null && list.size() > 0) {
			for (UserEntity userEntity : list) {
				if (StringUtils.isNotEmpty(userEntity.getLatitude()) && StringUtils.isNotEmpty(userEntity.getLongitude())) {
					Dict dict = Dict.create().set("position", new Double[]{new Double(userEntity.getLongitude()), new Double(userEntity.getLatitude())});
					dictList.add(dict);
				}
			}
		}
		return dictList;
	}

	@Override
	public UserEntity auth(String openId) {
		UserEntity userEntity = userMapper.selectOne(new QueryWrapper<UserEntity>().eq("wx_openid", openId));
		if (ObjectUtil.isNull(userEntity)) {
			throw new CustomApiException("没有授权的用户");
		}
		return userEntity;
	}

	@Override
	public UserEntity qqAuth(String openId) {
		UserEntity userEntity = userMapper.selectOne(new QueryWrapper<UserEntity>().eq("qq_openid", openId));
		if (ObjectUtil.isNull(userEntity)) {
			throw new CustomApiException("没有授权的用户");
		}
		return userEntity;
	}

	@Override
	public void agent(Long id) {
		//更新申请状态
		ApplyDriverEntity applyDriverEntity = applyDriverMapper.selectOne(new QueryWrapper<ApplyDriverEntity>().eq("user_id", id).eq("status", AppConsts.USER_APPLY_DRIVER_1));
		UserEntity user = userMapper.selectById(id);
		if(applyDriverEntity!=null){
			applyDriverEntity.setStatus(AppConsts.USER_APPLY_DRIVER_2);
			applyDriverMapper.updateById(applyDriverEntity);
			user.setName(applyDriverEntity.getName());
		}

		//todo 把申请的资料, 赋值给司机,并转换司机身份
		user.setApplyDriver(AppConsts.USER_APPLY_DRIVER_2);
		user.setRoleType(AppConsts.USER_ROLE_TYPE_2);
		if(userMapper.updateById(user)>0){
/*			if(user.getRoleType().equals(2)){
				try {
					SmsUtils.sendBatch(new ArrayList<>(Arrays.asList(user.getPhone())), SmsUtils.TemplateEnum.TEMPLATE_8);
				} catch (ClientException e) {
					e.printStackTrace();
				}
			}*/
		};
	}

	@Override
	public void refuse(UserEntity userEntity) {
		UserEntity user = userMapper.selectById(userEntity.getId());
		user.setApplyDriver(AppConsts.USER_APPLY_DRIVER_3);
		user.setApplyReason(userEntity.getApplyReason());
		userMapper.updateById(user);
		ApplyDriverEntity applyDriverEntity = applyDriverMapper.selectOne(new QueryWrapper<ApplyDriverEntity>().eq("user_id", user.getId()).eq("status", AppConsts.USER_APPLY_DRIVER_1));
		applyDriverEntity.setStatus(AppConsts.USER_APPLY_DRIVER_3);
		applyDriverEntity.setApplyReason(userEntity.getApplyReason());
		applyDriverMapper.updateById(applyDriverEntity);
	}

	@Override
	public void dealOrderMoney() {
		this.userMapper.dealOrderMoney();
	}

	@Override
	public List<UserVo> getSuperiorUserUser(Long superiorUserId) {
		List<UserVo> list = userMapper.getSuperiorUserUser(superiorUserId);
		return list;
	}

	@Override
	public void depositRefund(Long id) throws Exception {
		Integer count = userDepositMapper.selectCount(new QueryWrapper<UserDepositEntity>()
				.eq("user_id", id)
				.eq("status", AppConsts.USER_DEPOSIT_STATUS_1)
		);
		if (count > 0) {
			throw new CustomApiException("你已经申请过了");
		}
		UserDepositEntity userDepositEntity = new UserDepositEntity();
		userDepositEntity.setStatus(AppConsts.USER_DEPOSIT_STATUS_1);
		userDepositEntity.setUserId(id);
		userDepositMapper.insert(userDepositEntity);
	}

	@Override
	public void applyDriver(ApplyDriverEntity applyDriver) {
		UserEntity userEntity = userMapper.selectById(applyDriver.getUserId());
		if (userEntity == null) {
			throw new CustomApiException("没有这个用户");
		}


		ApplyDriverEntity applyDriverEntity = applyDriverMapper.selectOne(new QueryWrapper<ApplyDriverEntity>()
				.eq("user_id", applyDriver.getUserId())
		);
		UserEntity driver= userMapper.selectById(applyDriverEntity.getNewUserId());
		UserEntity driver1= userMapper.selectOne(new QueryWrapper<UserEntity>().eq("phone",userEntity.getPhone()).eq("role_type",2));
		if (driver!=null&&driver.getRoleType().equals(AppConsts.USER_ROLE_TYPE_2)) {
			throw new CustomApiException("你已经是司机");
		}
		if(driver1!=null){
			throw new CustomApiException("你已经是司机");
		}
		if (applyDriverEntity != null) {
			//修改
			applyDriver.setId(applyDriverEntity.getId());
			applyDriver.setStatus(AppConsts.USER_APPLY_DRIVER_1);
			applyDriverMapper.updateById(applyDriver);
		} else {
			userEntity.setId(null);
			userEntity.setPhone(applyDriver.getPhone());
			userEntity.setApplyDriver(AppConsts.USER_APPLY_DRIVER_1);
			this.userMapper.insert(userEntity);
			//添加
			applyDriver.setNewUserId(userEntity.getId());
			applyDriver.setStatus(AppConsts.USER_APPLY_DRIVER_1);
			applyDriverMapper.insert(applyDriver);
		}
		//修改用户状态为申请成为司机

	}

	@Override
	public ApplyDriverEntity getApplyDriverDetails(Long userId) {
		ApplyDriverEntity applyDriverEntity = applyDriverMapper.selectOne(new QueryWrapper<ApplyDriverEntity>().eq("user_id", userId));
		if (applyDriverEntity == null) {
			applyDriverEntity = new ApplyDriverEntity();
		}
		return applyDriverEntity;
	}

	@Override
	public Integer driverOpen(Long id) {
		UserEntity userEntity = userMapper.selectById(id);
		int count = orderMapper.selectCount(new QueryWrapper<OrderEntity>().eq("driver_id",userEntity.getId())
				.ge("status",AppConsts.ORDER_STATUS_1)
				.le("status",AppConsts.ORDER_STATUS_3)
		);
		if(count==0){
			userEntity.setDriverState(AppConsts.USER_DRIVER_STATE_2);
			userMapper.updateById(userEntity);
		}
		return count;
	}

	@Override
	public void driverOff(Long id) {
		UserEntity userEntity = userMapper.selectById(id);
		userEntity.setDriverState(AppConsts.USER_DRIVER_STATE_1);
		userMapper.updateById(userEntity);
	}

	@Override
	public UserEntity Wxlogin(Login form) {
		UserEntity user=userMapper.selectOne(new QueryWrapper<UserEntity>().eq("wx_cloud_openid",form.getOpenId()));
		return user;
	}

	@Override
	public UserEntity findByPhoneOrOpendId(String phone, String openId) {

		return userMapper.selectOne(new QueryWrapper<UserEntity>()
				.eq(phone!=null,"phone",phone)
				.eq(openId!=null,"ali_cloud_openid",openId)
				.eq("role_type",1)
				.eq("deleted",0)
		);
	}
}
